﻿
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Microsoft.Extensions.DependencyInjection;
using StudentInfoSystem.Core.Interfaces;
using StudentInfoSystem.Core.Models;
using StudentInfoSystem.Core.Models.Enums;
using System.Windows;
using ObservableObject = CommunityToolkit.Mvvm.ComponentModel.ObservableObject;
// 在文件顶部添加命名空间
using System.Text.RegularExpressions;

namespace StudentInfoSystem.UI.ViewModels.Windows
{
    public partial class StudentEditViewModel : ObservableObject
    {
        private readonly IStudentService _studentService;
        private readonly bool _isEditMode;

        [ObservableProperty]
        private Student _student;

        [ObservableProperty]
        private string _windowTitle;


        public Gender SelectedGender
        {
            get => _student.Gender;
            set => SetProperty(_student.Gender, value, _student, (s, g) => s.Gender = g);
        }



        public StudentEditViewModel()
        {
            _studentService = Bootstrapper.AppHost.Services.GetRequiredService<IStudentService>();
            _student = new Student();
            _windowTitle = "添加学生";
            _isEditMode = false;
            // 设置默认性别为男
            SelectedGender = 0;
        }

        public StudentEditViewModel(Student student)
        {
            _studentService = Bootstrapper.AppHost.Services.GetRequiredService<IStudentService>();
            _student = student;
            _windowTitle = "编辑学生";
            _isEditMode = true;

            // 根据学生性别设置SelectedGender
            SelectedGender = _student.Gender;

            // 创建学生对象的深拷贝
            _originalStudent = student;
            _editingStudent = new Student
            {
                Id = student.Id,
                Name = student.Name,
                Gender = student.Gender,
                College = student.College,
                Department = student.Department,
                Class = student.Class,
                Dormitory = student.Dormitory,
                Hometown = student.Hometown,
                Phone = student.Phone
            };
            Student = _editingStudent;
        }
        private readonly Student _originalStudent;
        private Student _editingStudent;
        // 添加此属性

        // 在Save方法中添加验证逻辑
        [RelayCommand]
        private void Save()
        {
            // 验证必填字段
            if (string.IsNullOrWhiteSpace(_student.Id))
            {
                MessageBox.Show("学号不能为空", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            if (string.IsNullOrWhiteSpace(_student.Name))
            {
                MessageBox.Show("姓名不能为空", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
            // 验证学号必须是数字
            if (!Regex.IsMatch(_student.Id, @"^\d+$"))
            {
                MessageBox.Show("学号必须为数字", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            // 验证姓名必须是中文或英文（允许空格）
            if (!Regex.IsMatch(_student.Name, @"^[\u4e00-\u9fa5a-zA-Z\s]+$"))
            {
                MessageBox.Show("姓名只能包含中文、英文和空格", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
            // 验证学院必须是中文或英文（允许空格），允许为空
            if (!Regex.IsMatch(_student.College, @"^(|[\u4e00-\u9fa5a-zA-Z\s]+)$"))
            {
                MessageBox.Show("学院只能包含中文、英文和空格", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            // 验证专业必须是中文或英文（允许空格），允许为空
            if (!Regex.IsMatch(_student.Department, @"^(|[\u4e00-\u9fa5a-zA-Z\s]+)$"))
            {
                MessageBox.Show("专业只能包含中文、英文和空格", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            // 验证生源地必须是中文或英文（允许空格），允许为空
            if (!Regex.IsMatch(_student.Hometown, @"^(|[\u4e00-\u9fa5a-zA-Z\s]+)$"))
            {
                MessageBox.Show("生源地只能包含中文、英文和空格", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            // 验证手机号必须是数字，允许为空
            if (!Regex.IsMatch(_student.Phone, @"^(|\d+)$"))
            {
                MessageBox.Show("手机号必须为数字", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }


            // 检查学号是否已存在（仅在添加模式下检查）
            if (!_isEditMode && _studentService.GetById(_student.Id) != null)
            {
                MessageBox.Show("学号已存在，请使用不同的学号", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            // 保存学生信息
            try
            {
                if (_isEditMode)
                {
                    _studentService.Update(_student);
                }
                else
                {
                    _studentService.Add(_student);
                }

                // 关闭窗口
                foreach (Window window in Application.Current.Windows)
                {
                    if (window.DataContext == this)
                    {
                        window.DialogResult = true;
                        window.Close();
                        break;
                    }
                }
            }
            catch (System.Exception ex)
            {
                MessageBox.Show($"保存失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
    }
}